package com.web.tools;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.web.pojo.MailAddress;

/**
 * 邮件发送工具类
 * 
 * @author xiaoyuhui
 *
 */
public class sendMailTool {
	// 设置服务器
	private static String VALUE_SMTP = "smtp.exmail.qq.com";
	// 发件人邮箱
	private String FROMADDRESS = "liaominjun@uinnova.com";
	// 发件人客户端专用密码
	private String FROMCLIENTPRIVATEPWD = "xxxxxxxxxxxx";
	// 建立会话
	private MimeMessage message;
	private Session s;

	/*
	 * 初始化
	 */
	public sendMailTool() {
		Properties props = System.getProperties();
		// 连接协议
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", VALUE_SMTP);
		// true一定要加双引号
		props.put("mail.smtp.auth", "true");
		// 设置是否使用ssl安全连接 ---一般都使用
		props.put("mail.smtp.ssl.enable", "true");
		// 设置是否显示debug信息 true 会在控制台显示相关信息
		props.put("mail.debug", "true");
		s = Session.getDefaultInstance(props);
		s.setDebug(true);
		message = new MimeMessage(s);
	}

	/**
	 * 发送邮件
	 */
	public void doSendHtmlEmail(String headName, StringBuilder sendHtml, MailAddress mailInfo) {
		try {
			// 发件人
			InternetAddress from = new InternetAddress(FROMADDRESS);
			message.setFrom(from);
			// 收件人
			InternetAddress to = new InternetAddress(mailInfo.getToAddr());
			message.setRecipient(Message.RecipientType.TO, to);
			// 抄送地址
			InternetAddress cc = new InternetAddress(mailInfo.getCcAddr());
			message.setRecipient(Message.RecipientType.CC, cc);
			// 邮件标题
			message.setSubject(headName);
			String content = sendHtml.toString();
			// 邮件内容,也可以使纯文本"text/plain"
			message.setContent(content, "text/html;charset=UTF-8");
			message.setSentDate(new Date());
			message.saveChanges();
			Transport transport = s.getTransport("smtp");
			// 这种方式应用于QQ邮箱,最后一个参数是授权码,也就是在客户端进微信绑定后，生成的客户端密码
			transport.connect(FROMADDRESS, FROMCLIENTPRIVATEPWD);
			// 发送
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}